package com.fujin.gulimall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.fujin.common.constant.ProductConstant;
import com.fujin.gulimall.product.Vo.AttrGroupRelationVo;
import com.fujin.gulimall.product.Vo.AttrResponseVo;
import com.fujin.gulimall.product.Vo.AttrVo;
import com.fujin.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.fujin.gulimall.product.dao.AttrGroupDao;
import com.fujin.gulimall.product.dao.CategoryDao;
import com.fujin.gulimall.product.entity.*;
import com.fujin.gulimall.product.service.CategoryService;
import com.fujin.gulimall.product.service.ProductAttrValueService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fujin.common.utils.PageUtils;
import com.fujin.common.utils.Query;

import com.fujin.gulimall.product.dao.AttrDao;
import com.fujin.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    AttrGroupDao attrGroupDao;
    @Autowired
    CategoryDao categoryDao;
    @Autowired
    CategoryService categoryService;
    @Autowired
    ProductAttrValueService productAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attrVo) {
        //将属性正常存储
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo,attrEntity);
        this.save(attrEntity);

        //为基本属性才需要保存属性分组
        if (attrVo.getAttrType() == 1) {
            //将属性分组id和属性id存入关联表
            AttrAttrgroupRelationEntity attrAttrgroup = new AttrAttrgroupRelationEntity();
            attrAttrgroup.setAttrId(attrEntity.getAttrId());
            attrAttrgroup.setAttrGroupId(attrVo.getAttrGroupId());
            attrAttrgroupRelationDao.insert(attrAttrgroup);
        }
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String type) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq(
                "attr_type","base".equalsIgnoreCase(type)? ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode():ProductConstant.AttrEnum.ATTR_TYPR_SALE.getCode());

        //当catelogId等于0时查询所有
        if (catelogId != 0){
            queryWrapper.eq("catelog_id",catelogId);
        }

        //条件查询
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((wrapper) -> {
                wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        PageUtils pageUtils = new PageUtils(page);

        List<AttrEntity> records = page.getRecords();

        List<AttrResponseVo> collect = records.stream().map(attrEntity -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);

            //设置属性分组名称和三级分类名称
            //根据属性id在"属性分组&属性关联表得到所属分组id"
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

            //根据分组id查询
            if (relationEntity != null) {
                if ("base".equalsIgnoreCase(type)) {
                    AttrGroupEntity attrgroup = null;
                        if (relationEntity.getAttrGroupId() != null) {
                            attrgroup = attrGroupDao.selectOne(
                                    new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", relationEntity.getAttrGroupId()));
                        }
                        if (attrgroup != null) {
                            attrResponseVo.setGroupName(attrgroup.getAttrGroupName());
                        }
                }
            }
            //根据三类分级id查询
            CategoryEntity categoryEntity = categoryDao.selectOne(
                    new QueryWrapper<CategoryEntity>().eq("cat_id", attrEntity.getCatelogId()));

            if (categoryEntity != null) {
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());

        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        //使用封装好的Vo对象返回给前端
        AttrResponseVo attrResponseVo = new AttrResponseVo();
        //查询当前属性信息，赋值给Vo对象
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity,attrResponseVo);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()) {
            //根据attrId在关联表中查询所属分组
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));

            if (relationEntity != null) {
                attrResponseVo.setAttrGroupId(relationEntity.getAttrGroupId());
            }

            //根据属性分组id查询对象 得到属性分组名称 进行赋值
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(relationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                attrResponseVo.setGroupName(attrGroupEntity.getAttrGroupName());
            }
        }

        //通过递归返回完整的三级分类路径
        Long[] pathByattrGroupId = categoryService.findPathByattrGroupId(attrEntity.getCatelogId());
        attrResponseVo.setCatelogPath(pathByattrGroupId);

        //查询三级分类名称
        CategoryEntity categoryEntity = categoryDao.selectById(attrResponseVo.getCatelogId());

        attrResponseVo.setCatelogName(categoryEntity.getName());
        return attrResponseVo;
    }

    @Transactional
    @Override
    public void updateAttr(AttrResponseVo attr) {
        //将传入的Vo对象赋值到AttrEntity对象 进行保存
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPR_BASE.getCode()) {
            //修改关联表信息
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationEntity.setAttrId(attr.getAttrId());

            Integer count = attrAttrgroupRelationDao.selectCount(
                    new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));

            //当找不到attr_id的数据时 进行保存操作 否则喂修改操作
            if (count != 0){
                attrAttrgroupRelationDao.update(relationEntity,
                        new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attr.getAttrId()));
            }else {
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    @Override
    public List<AttrEntity> getRelation(Long attrGroupId) {
        //根据分组id 从关联表中获取属性id
        List<AttrAttrgroupRelationEntity> relation = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));

        List<Long> attrIds = relation.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        if (attrIds == null || attrIds.size() <= 0){
            return null;
        }
        List<AttrEntity> attrEntities = this.listByIds(attrIds);

        return attrEntities;
    }

    @Override
    public void relationDelete(AttrGroupRelationVo[] attrGroupRelationVo) {
        List<AttrGroupRelationVo> relationVos = Arrays.asList(attrGroupRelationVo);
        //将传入的Vo对象转换为关联表对象
        List<AttrAttrgroupRelationEntity> collect = relationVos.stream().map((item) -> {
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, relationEntity);
            return relationEntity;
        }).collect(Collectors.toList());

        //批量移除属性分组&属性关联信息
        attrAttrgroupRelationDao.deleteBatchRelation(collect);
    }

    /**
     * 查询分组为关联的属性 只能获取自己分类下的属性
     * @param attrGroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils attrNoRelation(Long attrGroupId, Map<String, Object> params) {
        //1、根据分组id查询对象
        AttrGroupEntity groupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = groupEntity.getCatelogId();

        //2、当前分组只能关联自己所属的分类里面的属性
        //2.1)、得到分类下所有分组
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //得到所有分组id
        List<Long> collect = attrGroupEntities.stream().map((item) -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、得到这些分组已经关联的数据
        List<AttrAttrgroupRelationEntity> RelationEntities = attrAttrgroupRelationDao.selectList(
                new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));

        List<Long> attrIds = RelationEntities.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类中的所有属性去除"attrIds"这部分
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type",1);

        if (attrIds != null && attrIds.size() > 0){
            queryWrapper.notIn("attr_id", attrIds);
        }

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)){
            queryWrapper.and((Wrapper) -> {
               Wrapper.eq("attr_id",key).or().like("attr_name",key);
            });
        }

        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    @Override
    public List<ProductAttrValueEntity> listCatelogById(Long spuId) {
        //根据spu查询spu规格信息
        List<ProductAttrValueEntity> list = productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        return list;
    }

    /**
     * //根据attrId在属性表中查询可以检索的属性
     * @param attrIds
     * @return
     */
    @Override
    public List<Long> selectSearchAttrIds(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }

}